package com.nova.view;

import com.nova.source.R;

import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnKeyListener;
import android.text.SpannableStringBuilder;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.TextView;

public class NovaProgressDialog {
	private Dialog mDialog;
	private TextView mTextView;
	private Runnable cancelRunnable = new Runnable() {
		public void run() {
			if (NovaProgressDialog.this.mDialog != null &&NovaProgressDialog.this.mDialog.isShowing())
				//NovaProgressDialog.this.mDialog.cancel();
			NovaProgressDialog.this.mDialog.dismiss();
		}
	};

	public NovaProgressDialog(Context context) {
		this.mDialog = new Dialog(context, R.style.dialog);
//		dialog.setContentView(R.style.dialog);
		LayoutInflater inflater = LayoutInflater.from(context);
		View view = inflater.inflate(R.layout.dialog_progress, null);
		this.mTextView = ((TextView) view.findViewById(R.id.textview));
		setCancelable(false);
		this.mDialog.setContentView(view);
		this.mDialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
			public void onCancel(DialogInterface dialog) {
				NovaProgressDialog.this.mTextView.removeCallbacks(NovaProgressDialog.this.cancelRunnable);
			}
		});
		this.mDialog.show();

		this.mDialog.setOnKeyListener(new OnKeyListener() {

			@Override
			public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {

				if (keyCode == KeyEvent.KEYCODE_BACK) {
					mDialog.cancel();
				}
				return false;
			}
		});
	}

	public void setCancelable(boolean cancelable) {
		this.mDialog.setCancelable(cancelable);
	}

	public void setText(String text) {
		this.mTextView.setText(text);
	}
	public void setTextBuilder(SpannableStringBuilder builder) {
		this.mTextView.setText(builder);
	}
	public void setText(int textID) {
		this.mTextView.setText(textID);
	}

	public void show() {
		this.mTextView.removeCallbacks(this.cancelRunnable);
		if (!this.mDialog.isShowing())
			this.mDialog.show();
	}

	public void cancelImmediately() {
		this.mDialog.cancel();
	}

	public void cancel() {
		this.mTextView.postDelayed(this.cancelRunnable, 500L);
	}

}
